<?php
class Curl {
	private $_sCookie = null;
	private $_aPost = array ();
	private $_aHeader = array ();
	
	public function setCookie($sCookie = null) {
		if ($sCookie == null) {
			$sPath = ROOT . Base::getConf ( 'curl.cookie_path' );
			if (! is_dir ( $sPath )) {
				Base::$oBase->File_md ( $sPath );
			}
			$sCookie = Base::getConf ( 'curl.cookie' );
		}
		if ($sPath == null) {
			$sPath = ROOT;
		}
		if ($sCookie == null) {
			$sStr = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
			for($i = 0; $i < 32; $i ++) {
				$sStr = str_shuffle ( $sStr );
				$sCookie .= $sStr {0};
			}
			$sCookie = $sPath . '/' . $sCookie;
		}
		$this->_sCookie = $sCookie . '.cookie';
		touch ( $this->_sCookie );
		return $sCookie;
	}
	
	public function delCookie() {
		@unlink ( $this->_sCookie );
	}
	
	public function setCookiePath($sPath = null) {
		if ($sPath == null) {
			$sPath = Base::getConf ( 'curl.cookie_path' );
		}
	}
	
	public function addPost($sName, $sValue) {
		if ($sName == null) {
			$this->_aPost [] = $sValue;
		} else {
			$this->_aPost [] = $sName . '=' . urlencode ( $sValue );
		}
	}
	
	public function clearPost() {
		$this->_aPost = array ();
	}
	
	public function setHeader($sName, $sValue = null) {
		if (is_array ( $sName )) {
			foreach ( $sName as $k => $v ) {
				$this->setHeader ( $k, $v );
			}
		} else {
			$this->_aHeader [$sName] = $sValue;
		}
	}
	
	public function exec($sUrl) {
		$rCurl = curl_init ();
		curl_setopt ( $rCurl, CURLOPT_URL, $sUrl );
		curl_setopt ( $rCurl, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $rCurl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2' );
		if ($this->_aPost) {
			$sPost = implode ( '&', $this->_aPost );
			curl_setopt ( $rCurl, CURLOPT_POST, count ( $this->_aPost ) );
			curl_setopt ( $rCurl, CURLOPT_POSTFIELDS, $sPost );
		}
		if ($this->_sCookie) {
			curl_setopt ( $rCurl, CURLOPT_COOKIEJAR, $this->_sCookie );
			curl_setopt ( $rCurl, CURLOPT_COOKIEFILE, $this->_sCookie );
		}
		if (! empty ( $this->_aHeader )) {
			foreach ( $this->_aHeader as $k => $v ) {
				$aHeader [] = $k . ':' . $v;
			}
			curl_setopt ( $rCurl, CURLOPT_HTTPHEADER, $aHeader );
		}
		$sHtml = curl_exec ( $rCurl );
		if (! $sHtml) {
			$aInfo = curl_getinfo ( $rCurl );
			if ($aInfo ['http_code'] == 301 || $aInfo ['http_code'] == 302) {
				$aHeader = get_headers ( $sUrl, 1 );
				if (is_array ( $aHeader ['Location'] )) {
					$sLocation = $aHeader ['Location'] [0];
				} elseif ($aHeader ['Location']) {
					$sLocation = $aHeader ['Location'];
				} else {
					return false;
				}
				if (preg_match ( '/^https?:\/\/.+/i', $sLocation )) {
					$sHtml = self::exec ( $sLocation );
				} else {
					$aUrl = parse_url ( $sUrl );
					$sUrl = $aUrl ['scheme'] . '://' . $aUrl ['host'] . $sLocation;
					$sHtml = $this->exec ( $sUrl );
				}
			}
		}
		curl_close ( $rCurl );
		return $sHtml;
	}
}
?>